package com.shopping.service.webSocket;

import com.shopping.constant.ResponseCode;
import com.shopping.pojo.OfflineMessage;
import com.shopping.pojo.OfflineSys;
import com.shopping.service.offline.OfflineServiceImpl;
import com.shopping.service.user.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{userId}")
@Service
public class WebSocketServiceImpl implements WebSocketService {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSocketServices = new CopyOnWriteArraySet<>();
    private Session session;
    private int userId;
    @Autowired
    private OfflineServiceImpl offlineService;
    @Autowired
    private UserServiceImpl userService;

    public Session getSession() {
        return session;
    }

    public int getUserId() {
        return userId;
    }

    @OnOpen
    @Override
    public void onOpen(@PathParam("userId") int userId, Session session) {
        this.session = session;
        this.userId = userId;
        webSocketServices.add(this);
        addOnlineCount();
        System.out.println("有新连接加入，当前在线人数为: " + getOnlineCount());
        sendMessage(" id: " + userId + " 加入连接中");
        //查看是否有离线消息待处理
        Map<String, Object> map = offlineService.selectOffline(userId);
        if(Integer.parseInt(String.valueOf(map.get("code"))) == ResponseCode.REQUEST_SUCCESSED.getValue()){
            List<OfflineSys> offlineSysList = (List<OfflineSys>) map.get("offlineSysList");
            for(OfflineSys offlineSys: offlineSysList){
                //处理离线消息
                int senderId = offlineSys.getSenderId();
                Vector<OfflineMessage> messages = offlineSys.getMessage();
                for(OfflineMessage message : messages){
                    String sendMessage = message.getMessage();
                    sendMessage = "-1" + senderId + sendMessage;
                    onMessage(sendMessage, session);
                }
            }
            offlineService.deleteOffline(userId);
        }
    }

    @OnClose
    @Override
    public void onClose() {
        webSocketServices.remove(this);
        subOnlineCount();
        System.out.println("有一连接 id: " + this.getUserId() + "关闭，当前在线人数为: " + getOnlineCount());
    }

    @OnMessage
    @Override
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息: " + message);
        String userName = "";
        if(Integer.parseInt(message.split("[|]")[0]) == -1){
            userName = String.valueOf(userService.selectUserName(Integer.parseInt(message.split("[|]")[1])).get("userName"));
            message = message.substring(3 + userName.length());
        }else{
            userName = String.valueOf(userService.selectUserName(userId).get("userName"));
        }
        int receiverId = Integer.parseInt(message.split("[|]")[0]);
        String sendMessage = message.split("[|]")[1];
        for(WebSocketServiceImpl item: webSocketServices){
            if(item.getUserId() == receiverId){
                try{
                    item.sendMessage("from|" + userName + "|" + sendMessage);
                    return;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        //用户不在线
       offlineService.addOffline(userId, receiverId, message);
    }

    @OnError
    @Override
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送消息
     * @param message
     */
    private void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回在线数
     * @return
     */
    private static synchronized int getOnlineCount(){
        return onlineCount;
    }

    /**
     * 当连接人数增加时
     */
    private static synchronized void addOnlineCount(){
        WebSocketServiceImpl.onlineCount++;
    }

    /**
     * 当连接人数减少时
     */
    private static synchronized void subOnlineCount(){
        WebSocketServiceImpl.onlineCount--;
    }

}
